<?php

require_once('Zend/Db/Table/Row/Abstract.php');

class Core_User_Token
	extends Zend_Db_Table_Row_Abstract
{
	/**
	 * Token type: Google OpenID
	 * @var string
	 */
	const TYPE_GOOGLE = 'GOOGLE';
	
	/**
	 * Token type: LinkedIn OAuth
	 * 
	 * @var string
	 */
	const TYPE_LINKEDIN = 'LINKEDIN';
	
	/**
	 * Token type: Twitter OAuth
	 * 
	 * @var string
	 */
	const TYPE_TWITTER = 'TWITTER';
	
	/**
	 * Token type: Facebook OAuth
	 * 
	 * @var string
	 */
	const TYPE_FACEBOOK = 'FACEBOOK';
	
	/**
	 * Private static reference to the table.
	 * 
     * @return Zend_Db_Table
	 */
	private static $table;

	/**
	 * Name of the class of the Zend_Db_Table_Abstract object.
	 *
	 * @var string
	 */
	protected $_tableClass = 'Zend_Db_Table';

    /**
     * Select access method, for slightly more complex queries.
     *
     * @return Zend_Db_Table_Select
     */
    public static function getTableInstance()
    {
    	if ( empty(Core_User_Token::$table ) )
    	{
    		Core_User_Token::$table = new Zend_Db_Table('user_tokens');
    		Core_User_Token::$table->setRowClass('Core_User_Token');
    	}
    	
    	return Core_User_Token::$table;
    }
    
	/**
	 * Factory method. Finds a token or creates a new row record.
	 *
	 * @param  array $config OPTIONAL Array of user-specified config options.
	 * @return void
	 * @throws Zend_Db_Table_Row_Exception
	 */
	public static function factory( $id = null )
	{
    	$table = Core_User_Token::getTableInstance();
    	
    	if ( is_int($id) )
    	{
    		$row = $table->fetchRow( $table->select()->where('userTokenId=?',$id));
    	}
    	else
    	{
    		$row = $table->createRow(array(), Zend_Db_Table_Abstract::DEFAULT_DB);
    	}
    	
    	return $row;
	}

	/**
	 * Find a token by the user ID on the remote system.
	 *
	 * @param string $type
	 * @param id $remoteUserId
	 * @return Core_User_Token|null
	 */
	public static function findTokenByRemoteUserId ( $remoteUserId, $type )
	{
    	$table = Core_User_Token::getTableInstance();
		
    	$token = $table->fetchRow( $table->select()->where('type=?',$type)->where('remoteUserId=?',$remoteUserId));
		
    	return $token;
	}
	
	/**
	 * Find a token by the user ID on the current system
	 *
	 * @param string $type
	 * @param id $remoteUserId
	 * @return Core_User_Token|null
	 */
	public static function findTokenByUserId ( $userId, $type )
	{
    	$table = Core_User_Token::getTableInstance();
		
    	$token = $table->fetchRow( $table->select()->where('type=?',$type)->where('userId=?',$userId));
		
    	return $token;
	}

	/**
	 * @inheritDoc
	 */
	protected function _doInsert()
	{
		$this->created = new Zend_Db_Expr('NOW()');
		$this->updated = new Zend_Db_Expr('NOW()');
			
		parent::_doInsert();
	}

	/**
	 * @inheritDoc
	 */
	protected function _doUpdate()
	{
		$this->updated = new Zend_Db_Expr('NOW()');
			
		parent::_doUpdate();
	}
}